package com.monolithiot.sso.controller.device;

import com.monolithiot.sso.common.entity.DeviceAuthorization;
import com.monolithiot.sso.common.entity.User;
import com.monolithiot.sso.common.vo.BasicJsonResponse;
import com.monolithiot.sso.conf.prop.UploadFileConfigureProperties;
import com.monolithiot.sso.service.DeviceAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 2018/12/22 Create by 郭文梁
 * DeviceAuthorizationController
 * 设备授权数据访问控制器
 *
 * @author 郭文梁
 * @date 2018/12/22
 */
@RestController
@RequestMapping("/device/authorization")
public class DeviceAuthorizationController {
    private final DeviceAuthorizationService deviceAuthorizationService;
    private final UploadFileConfigureProperties uploadFileConfigureProperties;

    @Autowired
    public DeviceAuthorizationController(DeviceAuthorizationService deviceAuthorizationService, UploadFileConfigureProperties uploadFileConfigureProperties) {
        this.deviceAuthorizationService = deviceAuthorizationService;
        this.uploadFileConfigureProperties = uploadFileConfigureProperties;
    }

    /**
     * 检查授权，设备端发现本地有token时调用，检查授权是否有效
     *
     * @param deviceType 设备类型
     * @param token      令牌
     * @return BJR with DeviceAuthorization entity(with User entity)
     */
    @GetMapping("/{deviceType}/auth")
    public BasicJsonResponse<DeviceAuthorization> auth(
            @PathVariable("deviceType") Integer deviceType,
            @RequestParam("token") String token) {

        DeviceAuthorization authorization = deviceAuthorizationService.findByDeviceTypeAndTokenWithUser(deviceType, token);
        if (authorization == null) {
            return BasicJsonResponse.paramError("授权失败");
        }

        String prefix = uploadFileConfigureProperties.getPathPrefix() +
                "/" +
                uploadFileConfigureProperties.getUserHeadPortrait();
        User user = authorization.getUser();
        user = user.cloneAsPrettyPath(prefix);
        authorization.setUser(user);

        return BasicJsonResponse.ok(authorization);
    }
}
